use-same-route-navigation.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import { useEffect } from 'react';
  2. import { useRouter } from 'next/router';
  3. import { useFetchCurrentPage, useIsIdenticalPath } from '~/states/page';
  4. import { useSetEditingMarkdown } from '~/states/ui/editor';
  5. /**
  6. * This hook is a trigger to fetch page data on client-side navigation.
  7. * It detects changes in `router.asPath` and calls `fetchCurrentPage`.
  8. * The responsibility for determining whether to actually fetch data
  9. * is delegated to `useFetchCurrentPage`.
  10. */
  11. export const useSameRouteNavigation = (): void => {
  12. const router = useRouter();
  13. const isIdenticalPath = useIsIdenticalPath();
  14. const { fetchCurrentPage } = useFetchCurrentPage();
  15. const setEditingMarkdown = useSetEditingMarkdown();
  16. // useEffect to trigger data fetching when the path changes
  17. useEffect(() => {
  18. // If the path is identical, do not fetch
  19. if (isIdenticalPath) return;
  20. const fetch = async () => {
  21. const pageData = await fetchCurrentPage({ path: router.asPath });
  22. if (pageData?.revision?.body != null) {
  23. setEditingMarkdown(pageData.revision.body);
  24. }
  25. };
  26. fetch();
  27. }, [router.asPath, isIdenticalPath, fetchCurrentPage, setEditingMarkdown]);
  28. };